// .vuepress/client.js
import { defineClientConfig } from "@vuepress/client";
import { nextTick, onMounted, onUnmounted } from "vue";
import mermaid from "mermaid/dist/mermaid.esm.mjs";

// 1️⃣ 只初始化一次
mermaid.initialize({ startOnLoad: false, theme: "default" });

function renderMermaid() {
  if (typeof window === "undefined") return;
  nextTick(() => {
    const els = document.querySelectorAll(".mermaid");
    if (els.length) mermaid.init(els);
  });
}

export default defineClientConfig({
  enhance({ app, router }) {
    // 2️⃣ 路由切换后渲染
    router.afterEach(() => {
      setTimeout(() => {
        renderMermaid();
        console.log("Route changed, rendering Mermaid");
      }, 1000 * 2);
    });
  },

  setup() {
    // 初始渲染
    console.log("Initial setup, rendering Mermaid");
    renderMermaid();

    // 监听浏览器的 popstate 事件（后退/前进按钮）
    const handlePopState = () => {
      console.log("Popstate event, rendering Mermaid");
      renderMermaid();
    };

    // 添加事件监听器
    if (typeof window !== "undefined") {
      window.addEventListener("popstate", handlePopState);
    }

    // 清理事件监听器
    return () => {
      if (typeof window !== "undefined") {
        window.removeEventListener("popstate", handlePopState);
      }
    };
  },
});
